'use strict';
const db = uniCloud.database();
exports.main = async (event, context) => {
	//接收回调参数，创建应用内支付宝流水
	const balance = db.collection('balace_list');
	const arr = [];
	event = event.body.split('&');
	for(let i in event){
		arr.push(event[i].split('='));
	}
	let obj = {};
	obj.type = 2;
	obj.cerate_time = new Date().getTime();
	for(let j in arr){
		if(arr[j][0] == "app_id" ||					// app_id支付宝分配给开发者的应用 Id。
		   arr[j][0] == "version" ||				// version	调用的接口版本
		   arr[j][0] == "trade_no" ||				// trade_no支付宝交易号
		   arr[j][0] == "out_trade_no" ||			// out_trade_no商户订单号
		   arr[j][0] == "out_biz_no" ||				// out_biz_no	商户业务号
		   arr[j][0] == "buyer_logon_id" ||			// buyer_logon_id买家支付宝账号
		   arr[j][0] == "seller_email" ||			// seller_email卖家支付宝账号。
		   arr[j][0] == "trade_status" ||			// trade_status交易状态
		   arr[j][0] == "total_amount" ||			// total_amount订单金额
		   arr[j][0] == "appreceipt_amount_id"||	// receipt_amount实收金额
		   arr[j][0] == "buyer_pay_amount"			// buyer_pay_amount付款金额。用户在交易中支付的金额。
		){
			obj[`${arr[j][0]}`] = arr[j][1]
		}
	}
	obj.num = obj.total_amount;
	obj.desc = `购买了订单${obj.out_trade_no}的商品`
	//交易状态为支付成功时创建应用内支付宝流水
	if(obj.trade_status == "TRADE_SUCCESS"){
		const order = db.collection('order');
		const user = db.collection('user');
		const sign = db.collection('sign_in_user');
		//查询相关订单
		let or = await order.where({
			_id: obj.out_trade_no
		}).get();
		let de_or = await order.where({
			_id: obj.out_trade_no
		}).update({
			status: 1,
			pay_status: 2
		});
		// 创建应用内支付宝流水
		obj.user_id = or.data[0].user_detail.user_id;
		balance.add(obj);
		//创建积分流水
		let sign_pa = {
			user_id: obj.user_id,
			integral_number: or.data[0].integral,
			sign_time: new Date().getTime(),
			type: 2,
			descration: `用支付宝购买了订单${obj.out_trade_no}的商品`
		}
		sign.add(sign_pa);
		//更新用户积分
		let us_de = await user.where({_id: obj.user_id}).get();
		let n_integral = us_de.data[0].integral;
		let n_shopIntegral = us_de.data[0].shopIntegral;
		let u_integral = n_integral + or.data[0].integral;
		let u_shopIntegral = n_shopIntegral + or.data[0].integral;
		let up = await user.where({
			_id: obj.user_id
		}).update({
			integral: u_integral,
			shopIntegral: u_shopIntegral
		})
		console.log(up)
		return "success"
	}else {
		return "success"
	}
};
